use std::error::Error;
use std::sync::Arc;
use tokio::sync::Mutex;
use chrono::{DateTime, Utc};
use serde::{Serialize, Deserialize};

use crate::data::source::{DataSource, SectorIndex, MarketSentiment, VolumeDistribution, MarketBreadth};
use crate::config::data_source_config::DataSourceConfig;

/// 市场环境数据结构，包含所有市场环境相关的数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarketEnvironment {
    pub timestamp: DateTime<Utc>,
    pub sector_indices: Vec<SectorIndex>,
    pub market_sentiment: MarketSentiment,
    pub volume_distribution: VolumeDistribution,
    pub market_breadth: Option<MarketBreadth>,
}

/// 市场环境数据采集器，负责从数据源获取市场环境数据
pub struct MarketEnvironmentCollector {
    data_source: Arc<dyn DataSource + Send + Sync>,
    cache: Arc<Mutex<Option<(DateTime<Utc>, MarketEnvironment)>>>,
    config: DataSourceConfig,
}

impl MarketEnvironmentCollector {
    pub fn new(data_source: Arc<dyn DataSource + Send + Sync>, config: DataSourceConfig) -> Self {
        Self {
            data_source,
            cache: Arc::new(Mutex::new(None)),
            config,
        }
    }
    
    /// 获取完整的市场环境数据，包含板块指数、市场情绪、成交量分布等
    pub async fn get_market_environment(&self) -> Result<MarketEnvironment, Box<dyn Error + Send + Sync>> {
        // 检查缓存
        let cache_ttl = self.config.cache_ttl_seconds.unwrap_or(300); // 默认5分钟
        let now = Utc::now();
        
        {
            let cache = self.cache.lock().await;
            if let Some((timestamp, ref cached_data)) = *cache {
                let age = now.signed_duration_since(timestamp).num_seconds() as u64;
                if age < cache_ttl {
                    return Ok(cached_data.clone());
                }
            }
        }
        
        // 并行获取各类市场环境数据
        let sector_indices_future = self.data_source.get_sector_indices();
        let market_sentiment_future = self.data_source.get_market_sentiment();
        let volume_distribution_future = self.data_source.get_volume_distribution();
        let market_breadth_future = self.data_source.get_market_breadth();
        
        // 等待所有数据获取完成
        let (sector_indices, market_sentiment, volume_distribution, market_breadth) = tokio::join!(
            sector_indices_future,
            market_sentiment_future,
            volume_distribution_future,
            market_breadth_future
        );
        
        // 构建市场环境数据
        let market_environment = MarketEnvironment {
            timestamp: now,
            sector_indices: sector_indices?,
            market_sentiment: market_sentiment?,
            volume_distribution: volume_distribution?,
            market_breadth: market_breadth.ok(),
        };
        
        // 更新缓存
        let mut cache = self.cache.lock().await;
        *cache = Some((now, market_environment.clone()));
        
        Ok(market_environment)
    }
    
    /// 获取板块指数数据
    pub async fn get_sector_indices(&self) -> Result<Vec<SectorIndex>, Box<dyn Error + Send + Sync>> {
        self.data_source.get_sector_indices().await
    }
    
    /// 获取市场情绪指标
    pub async fn get_market_sentiment(&self) -> Result<MarketSentiment, Box<dyn Error + Send + Sync>> {
        self.data_source.get_market_sentiment().await
    }
    
    /// 获取成交量分布数据
    pub async fn get_volume_distribution(&self) -> Result<VolumeDistribution, Box<dyn Error + Send + Sync>> {
        self.data_source.get_volume_distribution().await
    }
    
    /// 获取特定板块的详细数据
    pub async fn get_sector_detail(&self, sector_code: &str) -> Result<serde_json::Value, Box<dyn Error + Send + Sync>> {
        // 在Python中调用get_sector_detail函数
        tokio::task::spawn_blocking(move || {
            pyo3::Python::with_gil(|py| {
                let data_collection = pyo3::types::PyModule::import(py, "data_collection")?;
                let detail_py = data_collection.getattr("get_sector_detail")?.call1((sector_code,))?;
                let detail: serde_json::Value = detail_py.extract()?;
                Ok::<_, Box<dyn Error + Send + Sync>>(detail)
            })
        }).await?
    }
}